package com.wu.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by wsq547 on 2021/10/4 19:20
 */
public class LoginInterceptor implements HandlerInterceptor {

    //在请求处理的方法之前执行
    //如果返回true执行下一个拦截器
    //如果返回false就不执行下一个拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("============处理前==========");

        HttpSession session = request.getSession();
        //放行：判断什么情况下是登录的
        //登录页面也放行
        if (request.getRequestURI().contains("toLoginPage")){
            return true;
        }

        //提交登录放行
        if (request.getRequestURI().contains("login")){
            return true;
        }

        //第一次登录是没有session的！！,登录后session不为空，不为空直接放行
        if (session.getAttribute("userLoginInfo")!=null){
            return true;
        }

        //判断什么情况是没有登录的,getRequestDispatcher转发到login页面
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);

        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("============处理后==========");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("===========清理==========");
    }
}
